package agents.task;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import agents.resource.ResourceAgent;



public class Trip implements Iterable<TripStep> {
	private List<TripStep> steps;

	//copy constructor
	public Trip(Trip t) {
		this.steps = new ArrayList<TripStep>(t.steps);
	}
	
	//construeert lege trip
	public Trip() {
		this.steps = new ArrayList<TripStep>();
	}
	
	public void append(TripStep step) {
		steps.add(step);
	}

	public TripStep getLastStep() {
		return steps.get(steps.size()-1);
	}
	public TripStep getFirstStep() {
		return steps.get(0);
	}
	
	public void removeStep(int index) {
		steps.remove(index);
	}

	public boolean passesBy(ResourceAgent out) {
		for(TripStep step : steps) {
			if(step.getResourceAgent() == out) return true;
		}
		return false;
	}
	
	//maakt mogelijk te itereren over de tripsteps
	public Iterator<TripStep> iterator() {
		return steps.iterator();
	}
	
	//kan schatting bevatten
	public long getEstimatedTotalTime() {
		return getLastStep().getEnterTime() + estimatedTimeLeft;
	}
	
	public void setEstimatedTimeLeft(long time) {
		estimatedTimeLeft = time;
	}
	
	long estimatedTimeLeft = 0;
	
	public boolean hasEstimation(){
		return estimatedTimeLeft != 0;
	}
	
	public String toString() {
		return "total: " + getEstimatedTotalTime() + ";" + steps.toString() + (hasEstimation()? ("+estimation "+estimatedTimeLeft):""); 
	}
	
	public List<TripStep> getAllSteps() {
		return new ArrayList<TripStep>(steps);
	}

	/**
	 * Checkt ofdat deze trip dezelfde route volgt als een andere trip
	 * Geeft ook true wanneer de route een (begin)deelroute is van de andere trip of vice versa
	 * @param otherTrip
	 * @return
	 */
	public boolean hasSameRouteAs(Trip otherTrip) {
		List<TripStep> mySteps = getAllSteps();
		List<TripStep> otherSteps = otherTrip.getAllSteps();
			
		for(int i = 0; i < getAllSteps().size(); i++) {
			ResourceAgent myResource= mySteps.get(i).getResourceAgent();
			
			if(i >= otherSteps.size()) return true;
			else {
				ResourceAgent otherResource = otherSteps.get(i).getResourceAgent();
				
				if(myResource != otherResource) {
					return (myResource == null || otherResource == null);
				}
			}
		}
		return true;
	}

}
